<?php
namespace app\home\controller;

use \app\common\controller\Homebase;
use \thans\Ret;
use \think\Loader;

class User extends Basic
{
    public function _initialize()
    {
        if (input('uid') == 1) {
            die('非法操作');
        }
        $this->user     = Loader::model('User');
        $this->auth     = Loader::model('Auth');
        $this->recharge = Loader::model('Recharge');
        /**
         * 管理员用户三级菜单
         */
        $this->umenu[0]['text'] = '管理员列表';
        $this->umenu[0]['url']  = 'index';
        /**
         * 会员三级菜单
         */
        $this->mmenu[0]['text'] = '会员列表';
        $this->mmenu[0]['url']  = 'member';
    }
    public function index()
    {
        $this->assign('third_menu', $this->umenu);
        $list = $this->user->where('is_del', 0)->where('user_type', 0)->paginate(10);
        $this->assign('list', $list);
        return $this->fetch();
    }
    /**
     * 会员列表页
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function member()
    {
        $this->assign('third_menu', $this->mmenu);
        $list = $this->user->where('is_del', 0)->where('user_type', 1)->paginate(10);
        $this->assign('list', $list);
        return $this->fetch();
    }
    /**
     * 编辑、添加会员
     * @return [type] [description]
     */
    public function add_member()
    {

        $this->assign('third_menu', $this->mmenu);
        return $this->fetch('edit_member');
    }
    public function edit_member()
    {
        $uid = input('uid');
        if ($uid) {
            $edit_res = $this->user->getUserById($uid);
            $this->assign('data', $edit_res);
            $this->assign('third_menu', $this->mmenu);
            return $this->fetch();
        }
    }

    public function go_add_member()
    {
        if (IS_POST) {
            $res = $this->user->saveUserInfo(input('post.'));
            if ($res['code']) {
                return $this->ret->setCode(0)->setAsk("新增成功,是否继续？")->toJson();
            } else {
                return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
            }

        }
    }

    public function go_edit_member()
    {
        $uid = input('uid');
        if (IS_POST) {
            $res = $this->user->saveUserInfo(input('post.'), $uid);
            if ($res['code']) {
                return $this->ret->setCode(0)->setMsg('更新成功')->setBack()->toJson();
            } else {
                return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
            }

        }
    }
    //修改会员状态
    public function change_status_m()
    {
        return $this->change_status();
    }
    //修改管理员状态
    public function change_status_u()
    {
        return $this->change_status();
    }
    protected function change_status()
    {
        $uid = input('uid');
        if ($uid == 1) {
            return $this->ret->setCode(1)->setMsg('禁止修改超级管理员状态!')->toJson();
        }
        $data['status'] = input('status');
        $res            = $this->user->where('user_id', $uid)->update($data);
        if ($res) {
            if ($data['status'] == 0) {
                $status = "停用";
            } else {
                $status = "启用";
            }
            return $this->ret->setCode(0)->setMsg($status)->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('修改状态失败')->toJson();
        }
    }
    /**
     * 删除会员
     * @return [type] [description]
     */
    public function del_m()
    {
        return $this->del();
    }
    /**
     * 删除用户
     * @return [type] [description]
     */
    public function del_u()
    {
        return $this->del();
    }
    /*
    根据用户删除用户
     */
    protected function del()
    {
        $uid = input('uid');
        if ($uid == 1) {
            return $this->ret->setCode(1)->setMsg('非法操作')->toJson();
        }
        $res = $this->user->where('user_id', $uid)->find();
        if (!$res || $res['is_del']) {
            return $this->ret->setCode(1)->setMsg('该用户不存在')->toJson();
        }
        $data['is_del'] = '1';
        $res            = $this->user->where('user_id', $uid)->update($data);
        if ($res) {
            return $this->ret->setCode(0)->setMsg('删除用户成功')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('删除用户失败')->toJson();
        }
    }
    /**
     * 用户添加（管理员）
     */
    public function add()
    {
        $this->assign('third_menu', $this->umenu);
        $list = $this->auth->select();
        $tree = $foo = new \thans\Common\tree($list);
        $tree->formatArrayForTree('auth_id', 'auth_name');
        $data = $tree->get_tree(0, "<option value='\$auth_id' \$selected>\$spacer \$auth_name </option>", 0);
        $this->assign('authlist', $data);
        return $this->fetch('edit');
    }
    public function edit()
    {
        $uid = input('uid');
        if ($uid) {
            $res = $this->user->getUserById($uid);
            if (!$res) {
                $this->error('非法操作');
            }
            $this->assign('data', $res);
            $select = $res['auth_id'];
            $this->assign('third_menu', $this->umenu);
            $list = $this->auth->select();
            $tree = $foo = new \thans\Common\tree($list);
            $tree->formatArrayForTree('auth_id', 'auth_name');
            $data = $tree->get_tree(0, "<option value='\$auth_id' \$selected>\$spacer \$auth_name </option>", $select);
            $this->assign('authlist', $data);
            return $this->fetch('edit');
        }

    }
    public function go_add()
    {
        $data['user_pwd']  = input('user_pwd');
        $res               = $this->user->checkForm($data, 'add_user');
        $data['user_name'] = input('user_name');
        $data['auth_id']   = input('auth_id');
        if (input('?status')) {
            $data['status'] = '1';
        } else {
            $data['status'] = '0';
        }
        $data['email'] = input('email');
        $res           = $this->user->checkForm($data);
        if ($res) {
            return $this->ret->setCode(1)->setMsg($res)->toJson();
        }
        $rand                  = inge_get_random_str(10);
        $data['user_pwd_rand'] = $rand;
        $data['user_pwd']      = inge_encryption_pwd(input('user_pwd'), $rand);
        $data['create_date']   = date('Y-m-d H:i:s', time());
        $data['create_ip']     = inge_get_ip();
        $res                   = $this->user->insert($data);
        if ($res) {
            return $this->ret->setCode(0)->setMsg('添加成功')->setBack()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('添加失败')->toJson();
        }
    }
    public function go_edit()
    {
        $uid = input('uid');
        if (IS_POST) {
            if (input('user_pwd')) {
                $rand                  = inge_get_random_str(10);
                $data['user_pwd_rand'] = $rand;
                $data['user_pwd']      = input('user_pwd');
            }
            $data['user_name'] = input('user_name');
            $data['auth_id']   = input('auth_id');
            if (input('?status')) {
                $data['status'] = '1';
            } else {
                $data['status'] = '0';
            }
            $data['email'] = input('email');
            $res           = $this->user->checkForm($data, 'edit_user');
            if ($res) {
                return $this->ret->setCode(1)->setMsg($res)->toJson();
            }
            if (input('user_pwd')) {
                $data['user_pwd'] = inge_encryption_pwd(input('user_pwd'), $rand);
            }
            $data['update_date'] = date('Y-m-d H:i:s', time());
            $res                 = $this->user->where($data)->find();
            if ($res) {
                return $this->ret->setCode(0)->setMsg('修改成功')->setBack()->toJson();
            } else {
                $res = $this->user->where('user_id', $uid)->update($data);
                if ($res) {
                    return $this->ret->setCode(0)->setMsg('修改成功')->setBack()->toJson();
                } else {
                    return $this->ret->setCode(1)->setMsg('修改失败')->toJson();
                }
            }

        }
    }
    /**
     * 个人信息展示、修改页面。
     * @return [type] [description]
     */
    public function profile()
    {
        $loglist = Loader::model('ActionsLog')->where('log_uid', session('u_id'))->where('log_a', 'dologin')->order('log_id desc')->paginate(10, false, [
            'query' => array('type' => 'loglist'),
        ]);
        $this->assign('type', input('type'));
        $this->assign('loglist', $loglist);
        return $this->fetch();
    }
    /**
     * 编辑个人信息
     * @return [type] [description]
     */
    public function edit_profile()
    {
        $uid                   = session('u_id');
        $data['user_nicename'] = input('user_nicename');
        $data['email']         = input('email');
        $data['mobile']        = input('mobile');
        $data['sex']           = input('sex');
        $data['user_url']      = input('user_url');
        $data['signature']     = input('signature');
        $data['sex']           = input('sex');
        $data['user_id']       = $uid;
        $res                   = $this->user->where($data)->find();
        if ($res) {
            return $this->ret->setCode(0)->setMsg("更新个人资料成功")->setReload()->toJson();
        } else {
            unset($data['user_id']);
            $res = $this->user->getUserByField('email', $data['email'], session('u_id'));
            if ($res) {
                return $this->ret->setCode(1)->setMsg("邮箱重复")->toJson();
            }
            $res = $this->user->getUserByField('mobile', $data['mobile'], session('u_id'));
            if ($res) {
                return $this->ret->setCode(1)->setMsg("手机号重复")->toJson();
            }
            $res = $this->user->getUserByField('user_nicename', $data['user_nicename'], session('u_id'));
            if ($res) {
                return $this->ret->setCode(1)->setMsg("昵称重复")->toJson();
            }

            $res = $this->user->checkForm($data, 'edit_profile');
            if ($res) {
                return $this->ret->setCode(1)->setMsg($res)->setReload()->toJson();
            }
            $res = $this->user->where('user_id', $uid)->update($data);
            if ($res) {
                return $this->ret->setCode(0)->setMsg("更新个人资料成功")->setReload()->toJson();
            } else {
                return $this->ret->setCode(1)->setMsg("更新个人资料失败")->toJson();
            }
        }
    }

    //充值操作
    public function add_recharge()
    {
        $user_id       = input('uid');
        $recharge_type = input('recharge_type');
        //$pay_status=input('pay_status');
        $true_money = numinput_to_num(input('recharge_money'));
        $data_now   = date('Y-m-d H:i:s', time());

        $result = $this->validate(
            [
                'recharge_type'  => $recharge_type,
                'recharge_money' => $true_money,
            ],
            [
                'recharge_type|选择类型'  => 'require|between:1,2|number',
                'recharge_money|充值金额' => 'require|number',
            ]
        );
        if ($result !== true) {
            return $this->ret->setCode(1)->setMsg($result)->setAsk('是否继续?')->toJson();
        }
        //用户数据维护：user_id，coin，score
        $user = array('user_id' => $user_id);
        if (empty($recharge_type)) {
            return $this->ret->setCode(1)->setMsg("请选择一个充值类型")->toJson();
        }
        if ($recharge_type == '1') {
            $user['coin']              = floatval($true_money);
            $recharge_data['pay_code'] = 'coin';
            $user['score']             = 0;
        } else {
            $user['score']             = intval($true_money);
            $recharge_data['pay_code'] = 'score';
            $user['coin']              = 0.00;
        }
        //此处进行交易状态判断（根据微信支付宝等返回参数判断）然后设置$recharge_data['pay_status']值


    	//创建唯一订单编号 用户名+昵称+当前时间的UNIX时间戳，进行MD5加密
    	$userinfo=$this->user->getUserById($user_id);
    	$recharge_order=time().'-'.$userinfo['user_id'].'-'.$userinfo['user_name'];
    	$recharge_data=array(
    			'user_id' =>$user_id,
    			'rech_order' =>$recharge_order,
    			'account' =>$true_money,
    			'rech_time'=>$data_now,
    			'pay_time'=>$data_now,
    			'pay_code'=>'',
    			'pay_name'=>'artificial',
    			'pay_status'=>'1',//默认给1，赋值前面设置的$recharge_data['pay_status']值
    	);
    	//调用事务提交数据
    	$res=$this->recharge->saveRecharge($user,$recharge_data);
    	//结果判断
    	if ($res == false){
    		return $this->ret->setCode(1)->setAsk('充值失败,是否继续?')->toJson();
    	}
    	return $this->ret->setCode(0)->setAsk('充值成功,是否继续?')->toJson();
    }
    
    //充值展示操作
    public function recharge(){
    	$user_id=input('uid');
  			if ($user_id) {
  				$edit_res = $this->user->getUserById($user_id);
  				$this->assign('data', $edit_res);
  				$this->assign('third_menu', $this->mmenu);
  				return $this->fetch();
  			}
  			return $this->redirect('home/user/member');
    }
    
    //充值记录展示
    public function recharge_list(){	
    	$user_name=input('user_name');
    	if (!empty($user_name)){
		    	$rechList=$this->recharge->alias('r')
		    						->join('__USER__ u ','r.user_id= u.user_id')
		    						-> where('r.pay_status',1)
		    						-> where('u.user_name','LIKE','%'.$user_name.'%')
		    						->order('rech_time desc')
		    						->paginate(10,false,['query'=>['user_name'=>$user_name]]);
    		}else {
		    	$rechList=$this->recharge->alias('r')
						    		->join('__USER__ u ','r.user_id= u.user_id')
						    		-> where('r.pay_status',1)
						    		->order('rech_time desc')
						    		->paginate(10);
    	}

    	$this->assign('rechlist', $rechList);
    	return $this->fetch();
    }
}
